<template>
    <!-- 表单 -->
    <el-form inline>
        <el-form-item label="精品课名称" style="width: 20%;">
            <el-input v-model="params.courseName" placeholder="请输入要搜索课程名称" />
        </el-form-item>
        <el-form-item label="教师名称" style="width:20%;">
            <el-select lable="" v-model="params.teacherId" placeholder="请选择教师名称" clearable>
                <el-option v-for="item in teacherSelectList" :key="item.teacherId" :label="item.nickName"
                    :value="item.teacherId" />
            </el-select>
        </el-form-item>
        <el-form-item label="状态" style="width:20%;">
            <el-select v-model="params.status" placeholder="请选择状态" clearable>
                <el-option label="新建课程" :value="0" />
                <el-option label="录制中" :value="1" />
                <el-option label="待审核" :value="2" />
                <el-option label="已发布" :value="3" />
                <el-option label="驳回" :value="4" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button @click="onSearch" plain>搜索</el-button>
            <el-button @click="onReset" plain type="info">重置</el-button>
            <el-button @click="onAddCourse" plain type="success">新增</el-button>
        </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table height="526px" :data="courseList">
        <el-table-column align="center" prop="courseId" label="课程id" />
        <el-table-column align="center" prop="courseName" label="课程名称" />
        <el-table-column align="center" prop="teacherName" label="教师名称" />
        <el-table-column align="center" prop="videoNum" label="视频数量" />
        <el-table-column align="center" label="课程状态">
            <template #default="{ row }">
                <el-tag 
                    :type="getStatusType(row.status)"
                >
                    {{ getStatusText(row.status) }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="200px" fixed="right">
            <template #default="{ row }">
                <el-button type="text" @click="onEdit(row.courseId)">编辑</el-button>
                <el-button type="text" @click="onReview(row.courseId)" v-if="row.status === 2">审核</el-button>
                <el-button type="text" class="red" @click="onDelete(row.courseId)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination background size="small" layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:current-page="params.pageNum" v-model:page-size="params.pageSize" :page-sizes="[5, 10, 20, 50]"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <course-drawer ref="courseEditRef" @success="onSuccess"></course-drawer>
</template>

<script setup>
import { reactive, ref, onMounted, provide } from 'vue';
import { getCourseListService, delCourseService } from '@/apis/course'
import CourseDrawer from "@/components/drawer/CourseDrawer.vue"
import { getTeacherSelectListService } from '@/apis/teacher'
import router from '@/router'


const params = reactive({
    pageNum: 1,
    pageSize: 10,
    courseName: '',
    teacherId: '',
    status: ''
})

// 状态文本映射
const getStatusText = (status) => {
    const statusMap = {
        0: '新建课程',
        1: '录制中',
        2: '待审核',
        3: '已发布',
        4: '驳回'
    };
    return statusMap[status] || '未知';
};

// 状态类型映射（用于设置不同颜色的标签）
const getStatusType = (status) => {
    const typeMap = {
        0: 'info',      // 灰色 - 新建课程
        1: 'warning',   // 黄色 - 录制中
        2: 'primary',   // 蓝色 - 待审核
        3: 'success',   // 绿色 - 已发布
        4: 'danger'     // 红色 - 驳回
    };
    return typeMap[status] || '';
};

const courseEditRef = ref()
const courseList = ref([])
const total = ref(0)

async function getCourseList() {
    const ref = await getCourseListService(params)
    courseList.value = ref.rows
    total.value = ref.total
}
getCourseList()

const teacherSelectList = ref([]);
const refreshKey = ref(0); // 用于强制刷新
async function getTeacherSelectList() {
    try {
        const res = await getTeacherSelectListService();
        teacherSelectList.value = res.data; // ✅ 正确赋值
        refreshKey.value += 1; // 强制刷新下拉框
    } catch (error) {
        console.error("加载教师列表失败:", error);
    }
}
onMounted(() => {
    getTeacherSelectList();
});
provide('teacherList', teacherSelectList);

function onSearch() {
    params.pageNum = 1
    getCourseList()
}

function onReset() {
    params.pageNum = 1
    params.pageSize = 10
    params.courseName = ''
    params.teacherId = ''
    params.status = ''
    getCourseList()
}

function handleSizeChange(newSize) {
    params.pageNum = 1
    getCourseList()
}

function handleCurrentChange(newPage) {
    getCourseList()
}


// 添加教师
const onAddCourse = () => {
    courseEditRef.value.open()
}


function onSuccess(service) {
    if (service === 'add') {
        params.pageNum = 1
    }
    getCourseList()
}

async function onDelete(courseId) {
    const isConfirmed = window.confirm("确定要删除该精品课程吗？");
    if (isConfirmed) {
        // 用户点击确认
        await delCourseService(courseId);
        params.pageNum = 1;
        getCourseList();
    } else {
        // 用户点击取消
        console.log("删除操作已取消");
    }
}
async function onEdit(courseId) {
    courseEditRef.value.open(courseId)
}

// 审核课程，跳转到课程详情页面
function onReview(courseId) {
    router.push(`/tims/courseDetails?courseId=${courseId}`)
}
</script>